package rssmanager.servlets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.*;

import rssmanager.service.*;


/**
 * Servlet implementation class InscriptionServlet
 */
public class InscriptionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor. 
	 */
	public InscriptionServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * si l'utilisateur tape l'adresse de la servlet directement dans la barre d'adresse, il est renvoyé 
		 * sur la page d'accueil !
		 */
		response.sendRedirect("home.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		// on récupère les valeurs des deux champs du formulaire de la page de login
		ResultSet rs;
		String error="", msg="";
		String pseudo = request.getParameter("pseudo");
		String email = request.getParameter("email");
		String mdp = request.getParameter("pass");
			
		try {
			PreparedStatement stmt = DBConnect.getConnection().prepareStatement("SELECT ID_USER FROM Users WHERE pseudo = ? OR email = ?");
			stmt.setString(1, pseudo);
			stmt.setString(2, email);
			stmt.execute();
			rs = stmt.getResultSet();

			if(rs.next()) { 
				error="Ce pseudo ou cet email est d&eacute;j&agrave; utilis&eacute; !";
			} else {		
				msg="Votre compte a &eacute;t&eacute; cr&eacute;&eacute; !";
				stmt = DBConnect.getConnection().prepareStatement("INSERT INTO Users VALUES (NULL,'" + pseudo + "','" + email + "','" + mdp + "')");
				stmt.executeUpdate();		
			}
			request.setAttribute("msg", msg);
			request.setAttribute("error", error);
            rs.close();                                                               
            stmt.close();                                                             
            stmt = null;   
            
			request.getRequestDispatcher("home.jsp").forward(request, response);
		}
		catch(Exception e){
			System.out.println("Connection ratée: "+e);
			System.exit(-1);   
		}
	}
}	
